<template>
  <div>
    <h1>修改密码</h1>
    <el-form :model="upForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="旧密码" prop="old">
        <el-input type="password" v-model="upForm.old" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new">
        <el-input type="password" v-model="upForm.new" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="checkNew">
        <el-input type="password" v-model="upForm.checkNew" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">修改</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "UserCenter",
  methods: {
    submitForm() {
      this.$refs["ruleForm"].validate((valid)=>{
        if(valid){
          this.$confirm("确定修改？","提示",{type: "warning"
          }).then(()=>{
            this.$axios.put("/user/upPassword",this.upForm).then((res)=>{
              this.$message.success(res.data.msg)
              this.$refs["ruleForm"].resetFields();
            })
          }).catch(()=>{
            this.$message.info("已取消修改")
          })

        }else{
          this.$message.error("请输入正确的信息！")
          return false;
        }
      })
    },
    resetForm() {
      this.$refs["ruleForm"].resetFields();
    }
  },
  data(){
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.upForm.checkNew !== '') {
          this.$refs.ruleForm.validateField('checkNew');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.upForm.new) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return{
      upForm:{
        old:'',
        new:'',
        checkNew:'',
      },
      rules:{
        old:[{
          required: true, message: '请输入旧密码', trigger: 'blur'
        }],
        new: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkNew: [
          { validator: validatePass2, trigger: 'blur' }
        ],

      }
    }

  },
}
</script>

<style scoped>
.el-form{
  width: 350px;
  margin: 0 auto;
}
</style>